package com.huo.com.mdxinterface;
import com.huo.com.mdxzhujie.CheckMDX;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;


@Component
public class MyIntercepter implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod=(HandlerMethod)handler;

        CheckMDX methodAnnotation = handlerMethod.getMethodAnnotation(CheckMDX.class);

        if(methodAnnotation!=null){
            System.out.println("--------------"+0);
            String token = request.getParameter("token");
            return checkToken(token);

        }else{
            return true;
        }

    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public boolean checkToken(String token){

        String value = redisTemplate.opsForValue().get(token);

        if(value!=null){

            return redisTemplate.delete(token);
        }else{
            return false;
        }

    }


    /**
     *  使用lua脚本检测token
     * @param token
     * @return
     */
    public boolean checkToken2(String token){

        String check="if redis.call('get',KEYS[1]) then return redis.call('del',KEYS[1]) else return 0 end";

        DefaultRedisScript<Long> defaultRedisScript=new DefaultRedisScript<>();
        defaultRedisScript.setScriptText(check);
        defaultRedisScript.setResultType(Long.class);

        Long execute = redisTemplate.execute(defaultRedisScript, Collections.singletonList(token));

        if(execute==1){
            return true;
        }else{
            return false;
        }

    }



}
